class ListNode {
    public int val;
    public ListNode next;

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val,ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class MergeTwoLists {
    public static void main(String[] args) {
        ListNode p1 = new ListNode(1);
        ListNode p2 = new ListNode(3);
        ListNode p3 = new ListNode(4);
        ListNode p4 = new ListNode(9,null);
        p1.next = p2;
        p2.next = p3;
        p3.next = p4;

        ListNode q1 = new ListNode(2);
        ListNode q2 = new ListNode(3);
        ListNode q3 = new ListNode(7);
        ListNode q4 = new ListNode(8,null);
        q1.next = q2;
        q2.next = q3;
        q3.next = q4;

        ListNode newNode = MergeLists(p1,q1);
        while (newNode != null) {
            System.out.print(newNode.val + " -> ");
            newNode = newNode.next;
        }
    }

    public static ListNode MergeLists(ListNode head1,ListNode head2) {
        //特例检查
        if(head1 == null || head2 == null) {
            return head1 == null ? head1 : head2;
        }
        //设置返回的头节点
        ListNode head = head1.val <= head2.val ? head1 : head2;
        ListNode cur1 = head.next;
        ListNode cur2 = head == head1 ? head2 : head1;
        ListNode pre = head;

        while(cur1 != null && cur2 != null ) {
             if(cur1.val <= cur2.val) {
                 pre.next = cur1;
                 cur1 = cur1.next;
             }
             else {
                 pre.next = cur2;
                 cur2= cur2.next;
             }
             pre = pre.next;
        }
        pre.next = cur1 != null ? cur1 : cur2;
        return head;
    }
}


